package com.forever.user.service;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.forever.entity.User;
import com.forever.user.dao.UserDataDao;
import com.forever.user.manager.MulitiThreadManager;
import com.forever.util.CommonField;

@Service
@Transactional
public class UserDataServiceImpl implements UserDataService {

	private Logger logger = Logger.getLogger(UserDataServiceImpl.class);
	@Autowired
	private UserDataDao userDataDao;
	@Autowired
	private MulitiThreadManager manager;
	@Autowired
	private RedisTemplate<String, User> redisTemplate;
	@Autowired
	private TaskExecutor taskExecutor;

	@Override
	public void toAdd(String id) {
		User u = (User) redisTemplate.opsForValue().get(id);
		if (null == u) {
			logger.info("get data by id[" + id + "] from redis is null!");
			User user = userDataDao.get(id);
			if (null != user) {
				redisTemplate.opsForValue().set(id, user);
				logger.info("set data by id[" + id + "] to redis!");
			}
		} else {
			// 5秒过期
			redisTemplate.boundValueOps(id).expire(5000, TimeUnit.SECONDS);
			logger.info("get data by id[" + id + "] from redis!");
		}
		taskExecutor.execute(new Runnable() {
			@Override
			public void run() {
				manager.randomGet(CommonField.THOUSAND_INT);
			}
		});
	}

	@Override
	public void saveUser(User user) {
		userDataDao.saveUser(user);
	}

	@Override
	public List<User> getAll() {
		return userDataDao.getAll();
	}
}